starter.controller('orderPayController', function($rootScope,$state,$ionicPopup,$timeout,$scope,Page, localStore,$location) {


    //console.log($state);
    var orderId = $state.params.orderId;
    if(orderId == "" || orderId == undefined) {
        Page.notice("操作异常，订单id未找到!");
        $state.go("orders");
        return;
    }
    //o0UQTwfJTCoGazbasKcYGqX3LTTY
    var openId = $rootScope.user.openId;
    Page.ajaxPost('app/wxMpPay/getJSSDKPayInfo.do',{orderId:orderId,openId : openId}, function(resp) {
        if (typeof WeixinJSBridge == "undefined"){
            if( document.addEventListener ){
                document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
            }else if (document.attachEvent){
                document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
            }
        }else{
            //Page.alert(angular.toJson(resp.data.datum));
            $scope.onBridgeReady(resp.data);
        }
    });

    $scope.onBridgeReady = function(orderData) {
        $scope.tradeNo = orderData.datum.tradeNo;
        WeixinJSBridge.invoke(
            'getBrandWCPayRequest', {
                "appId" : orderData.datum.appId,     //公众号名称，由商户传入
                "timeStamp": orderData.datum.timeStamp,         //时间戳，自1970年以来的秒数
                "nonceStr" : orderData.datum.nonceStr, //随机串
                "package" : orderData.datum.package,
                "signType" : orderData.datum.signType,         //微信签名方式:
                "paySign" : orderData.datum.paySign   //微信签名
            },function(res){
                //Page.alert(angular.toJson(res));
                if(res.err_msg == "get_brand_wcpay_request:ok"){
                    Page.ajaxPost('app/order/pay/completed.do',{tradeNo:$scope.tradeNo}, function(resp) {
                        Page.notice("支付已提交，扣款中请稍候...");
                        $state.go("orders");
                    });

                }else if(res.err_msg == "get_brand_wcpay_request:cancel"){
                    Page.ajaxPost('app/order/pay/canceled.do',{tradeNo:$scope.tradeNo}, function(resp) {
                        Page.notice("您已手动取消支付该订单");
                        $state.go("orders");
                    });

                }else{
                    alert("支付失败!失败原因:" + res.err_msg);
                }
            });
    };
		
});